package com.shiyi.config;

import com.shiyi.pojo.Configration;
import com.shiyi.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

/**
 * @Descrption
 * @Author: 十一
 * @Date: 2020/11/9 14:44
 * @Version V5.0
 **/
public class MapperConfigBuilder {

    public void parse(Configration configration, InputStream is) throws DocumentException {
        Document document = new SAXReader().read(is);
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");
        List<Element> list = rootElement.selectNodes("//select");
        for (Element element : list) {
            parseNode(configration, namespace, element);
        }

        List<Element> insertList = rootElement.selectNodes("//insert");
        for (Element element : insertList) {
            parseNode(configration, namespace, element);
        }
        List<Element> updateList = rootElement.selectNodes("//update");
        for (Element element : updateList) {
            parseNode(configration, namespace, element);
        }

        List<Element> deleteList = rootElement.selectNodes("//delete");
        for (Element element : deleteList) {
            parseNode(configration, namespace, element);
        }
    }

    private void parseNode(Configration configration, String namespace, Element element) {
        String id = element.attributeValue("id");
        String parameterType = element.attributeValue("parameterType");
        String resultType = element.attributeValue("resultType");
        String sqlText = element.getTextTrim();
        MappedStatement mappedStatement = new MappedStatement(id, resultType, parameterType, sqlText);
        String key = namespace + "." + id;
        configration.getSqlMapStatementMap().put(key, mappedStatement);
    }
}
